//
//  SYMomentsViewController.m
//  BSHOUYIFANG
//
//  Created by 曹雁彬 on 15/8/13.
//  Copyright (c) 2015年 CYB. All rights reserved.
//

#import "SYMomentsViewController.h"
#import "Header.h"
#import "SYMomentsFirstTableViewController.h"
#import "SYMomentsTypeTableViewController.h"
#import "MYRequestManger.h"
#import "SYMomentsTypeModel.h"
#import "LORefresh.h"




@interface SYMomentsViewController ()<UIScrollViewDelegate,SYMomentsTypeTableViewDelegate>
@property (nonatomic,strong)UIScrollView *tagSV;  //标签的滑动视图
@property (nonatomic,strong)NSMutableArray *tagArr;  //存放标签的数组
@property (nonatomic,assign)CGFloat tagLenth;  //存储标签总长度
@property (nonatomic,strong)NSMutableArray *tagLengthArr;  //存放每个标签长度的数组
@property (nonatomic,strong)UIView *tagLineView;  //标签与其他界面分界线
@property (nonatomic,strong)NSMutableArray *tagButtonArr;  //存放标签button的数组
@property (nonatomic,assign)NSInteger tagIndex;  //用来标记被选中的标签
@property (nonatomic,strong)UIScrollView *mainScrollView;  //主界面的滑动视图
@property (nonatomic,strong)SYMomentsFirstTableViewController *fstTVC;  //二级界面控制器
@property (nonatomic,strong)SYMomentsTypeTableViewController *typeVC;  //一级界面控制器
@property (nonatomic,strong)SYMomentsTypeTableViewController *secTypeVC;  //一级界面控制器
@property (nonatomic,strong)NSMutableArray *dataArr;  //数据数组
@property (nonatomic,strong)NSMutableArray *urlStrArr;  //接口数组
@property (nonatomic,strong)NSMutableArray *secDataArr;  //数据数组
@property (nonatomic,assign)NSInteger sign;  //标记该哪个控制器请求数据
@end

@implementation SYMomentsViewController
-(instancetype)init
{
    if (self = [super init]) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        //1.注册观察者 不断监测通知中心里面有没有我想要的通知
        [center addObserver:self selector:@selector(changetitle:) name:@"moonlight" object:nil];
    }
    return self;
  
}
- (void)changetitle:(NSNotification*)tification
{
    _titleStr = tification.userInfo[@"title"];
    NSLog(@"%@",_titleStr);
    
}

-(void)dealloc
{
    //移除观察者
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"moonlight" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //*************设置navigation属性*************//
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"教 程";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.leftBarButtonItem = anotherButton;
    //*************属性初始化*************//
    
    _dataArr = [NSMutableArray arrayWithCapacity:0];
    _secDataArr = [NSMutableArray arrayWithCapacity:0];
    _tagArr = [[NSMutableArray alloc]initWithCapacity:0];
    _tagLengthArr = [[NSMutableArray alloc]initWithCapacity:0];
    _tagButtonArr = [[NSMutableArray alloc]initWithCapacity:0];
    _tagLenth = 0;
    NSArray *arr = @[@"推荐",@"教程",@"布艺",@"编织",@"视频",@"皮艺",@"手工皂",@"植物",@"亲子",@"串珠",@"官方",@"粘土",@"美食",@"刺绣",@"头饰",@"综合"];
    _tagArr = [arr mutableCopy];
    NSArray *array = @[@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=0&V=1.1.3&mquan_id=556&F=ios&key=14394612092903607185&user_id=&sign=23ff70f7ae670756419a9607&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=700&V=1.1.3&mquan_id=556&F=ios&key=1439461143475662755&user_id=&sign=93338e001f8771c5ee7165f4&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=691&V=1.1.3&mquan_id=556&F=ios&key=14394603921421659417&user_id=&sign=026028727f905affefb33bb9&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=692&V=1.1.3&mquan_id=556&F=ios&key=14394604104041341253&user_id=&sign=adabecb1848f65cb3049d1c9&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=698&V=1.1.3&mquan_id=556&F=ios&key=1439460426174738237&user_id=&sign=5abe1adbeafaaad21eaf0450&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=694&V=1.1.3&mquan_id=556&F=ios&key=14394604481179018778&user_id=&sign=34574fd40aa77fa761b52f5d&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=690&V=1.1.3&mquan_id=556&F=ios&key=14394604602372702626&user_id=&sign=258323cec88017bb79a0b89b&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=738&V=1.1.3&mquan_id=556&F=ios&key=14394604733660710636&user_id=&sign=4b312c273f7c8be2bdef3daa&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=754&V=1.1.3&mquan_id=556&F=ios&key=14397835033439486182&user_id=560797&sign=6bb977fa3d5aa29cf468656e&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=693&V=1.1.3&mquan_id=556&F=ios&key=1439460499618350056&user_id=&sign=369d8ec6de4fab79f3159710&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=1047&V=1.1.3&mquan_id=556&F=ios&key=14394605122155673268&user_id=&sign=394619ca2335c04d3c4c2525&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=753&V=1.1.3&mquan_id=556&F=ios&key=1439460526963159201&user_id=&sign=08ec5d2e336d4d04eed81b4f&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=696&V=1.1.3&mquan_id=556&F=ios&key=14394605381135617798&user_id=&sign=ec83759d28165454bd2f8ba2&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=887&V=1.1.3&mquan_id=556&F=ios&key=14394608772984131779&user_id=&sign=37ce0fa675400292e855350a&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=825&V=1.1.3&mquan_id=556&F=ios&key=14394608332918102559&user_id=&sign=359d0390ea4cd6ec59b4782b&page=1",@"http://sdxapp.com/api/get.html?act=GetQuanList&tag_id=699&V=1.1.3&mquan_id=556&F=ios&key=14394606061050920755&user_id=&sign=1c87be00b99ef05413d8671f&page=1"];
    _urlStrArr = [array mutableCopy];
    if (_sign == 0) {
        [self parserDataWithIndex:0];
    }

    
    //*************tag的scrollview开辟*************//
    
    _tagSV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    _tagSV.showsHorizontalScrollIndicator = NO;
    _tagSV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tagSV];
    [self widthForTag];
    
    //*************主界面的scrollview开辟*************//
    
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT - 153)];
    _mainScrollView.backgroundColor = [UIColor colorWithRed:247 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:1];
    _mainScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * _tagArr.count, 0);
    _mainScrollView.pagingEnabled = YES;
    _mainScrollView.userInteractionEnabled = YES;
    _mainScrollView.delegate = self;
    [self.view addSubview:_mainScrollView];
    
    //*************以及界面控制器*************//
    
    _typeVC = [[SYMomentsTypeTableViewController alloc]initWithStyle:UITableViewStylePlain];
    _typeVC.tableView.frame = CGRectMake(0, 10, SCREEN_WIDTH, SCREEN_HEIGHT - 163);
    _typeVC.delegate = self;
    
//    __weak SYMomentsViewController *mVC = self;
//    __weak NSMutableArray *newArr = _dataArr;
//    __weak NSInteger parserINdex = _parserIndex;
//    [_typeVC.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
//        _refreshType = RefreshTypeNew;
//        _page = 1;
//        [newArr removeAllObjects];
//        [mVC reparserDataWithIndex:parserINdex];
//    }];
//    [_typeVC.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
//        _page = _page + 1;
//        _refreshType = RefreshTypeMore;
//        [mVC reparserDataWithIndex:parserINdex];
//    }];
    [_mainScrollView addSubview:_typeVC.tableView];
    
    _secTypeVC = [[SYMomentsTypeTableViewController alloc]initWithStyle:UITableViewStylePlain];
    _secTypeVC.tableView.frame = CGRectMake(SCREEN_WIDTH, 10, SCREEN_WIDTH, SCREEN_HEIGHT - 163);
    _secTypeVC.delegate = self;
    [_mainScrollView addSubview:_secTypeVC.tableView];
    
    //*************分界线*************//
    
    UIView *horizontalLine = [[UIView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 0.3)];
    horizontalLine.backgroundColor = [UIColor grayColor];
    [self.view addSubview:horizontalLine];
}



#pragma mark --数据请求

   //*************第一个控制器的数据请求*************//

- (void)parserDataWithIndex:(NSInteger)index{
    [MYRequestManger manager:GET RequestWith:_urlStrArr[index] parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *arr = dict[@"data"];
        [_dataArr removeAllObjects];
        for (NSDictionary *dic in arr) {
            SYMomentsTypeModel *model = [[SYMomentsTypeModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArr addObject:model];
        }
        _typeVC.dataArr = _dataArr;
        _sign = 2;
        [_typeVC.tableView reloadData];
        [_typeVC.tableView.defaultHeader endRefreshing];
        [_typeVC.tableView.defaultFooter endRefreshing];
    } error:^(NSError *error) {
        
    }];
}

   //*************第二个控制器的数据请求*************//

- (void)parserWithOtherIndex:(NSInteger)index{
    [MYRequestManger manager:POST RequestWith:_urlStrArr[index] parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *arr = dict[@"data"];
        [_secDataArr removeAllObjects];
        for (NSDictionary *dic in arr) {
            SYMomentsTypeModel *model = [[SYMomentsTypeModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_secDataArr addObject:model];
        }
        _secTypeVC.dataArr = _secDataArr;
        [_secTypeVC.tableView reloadData];
    } error:^(NSError *error) {
        
    }];
}


#pragma mark --tag滑动事件

   //*************tag自适应宽度*************//

- (void)widthForTag{
    for (int i = 0; i < _tagArr.count; i++) {
        UIButton *tagButton = [UIButton buttonWithType:UIButtonTypeSystem];
        tagButton.titleLabel.font = [UIFont systemFontOfSize:15];
        //tag自适应宽度
        NSString *tag = _tagArr[i];
        CGFloat width = [tag boundingRectWithSize:CGSizeMake(0, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName] context:nil].size.width;
        //创建tagButton
        tagButton.frame = CGRectMake(_tagLenth + 10 * (i + 1), 0, width, 40);
        [tagButton setTitle:tag forState:UIControlStateNormal];
        tagButton.tag = 3000 + i;
        [tagButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [tagButton addTarget:self action:@selector(changeMoments:) forControlEvents:UIControlEventTouchUpInside];
        [_tagButtonArr addObject:tagButton];
        
        [_tagSV addSubview:tagButton];
        _tagLenth += (width + 10);
        [_tagLengthArr addObject:@(width)];
    }
    
    _tagLineView = [[UIView alloc]initWithFrame:CGRectMake(10, 37, [_tagLengthArr[0] floatValue], 3)];
    _tagLineView.backgroundColor = [UIColor redColor];
    [_tagSV addSubview:_tagLineView];
    _tagSV.contentSize = CGSizeMake(_tagLenth + 150, 0);
}


   //*************首页跳转方法*************//

-(void)viewWillAppear:(BOOL)animated
{
    
    for (int i = 0; i < _tagArr.count; i++) {
        if ([_titleStr isEqualToString:_tagArr[i]]) {
            _sign = 1;
            [self changeMoments:_tagButtonArr[i]];
            return;
        }
    }
}


- (void)viewWillDisappear:(BOOL)animated{
    _titleStr = @"";
}


   //*************tag滑动方法*************//

- (void)changeMoments:(UIButton *)sender{
    //判断能否滑动
    CGFloat contentWidth = SCREEN_WIDTH - 40;
    if (_tagSV.contentSize.width < contentWidth) {
        [UIView animateWithDuration:0.2 animations:^{
            _tagLineView.frame = CGRectMake(sender.frame.origin.x, 37, sender.frame.size.width, 3);
            _mainScrollView.contentOffset = CGPointMake((sender.tag - 3000) * SCREEN_WIDTH, 0);
            [self reparserDataWithIndex:(sender.tag - 3000)];
        }];
        return;
    }
    _tagIndex = sender.tag - 3000 + 1;
    //判断最后一个tag的点击事件
    if (_tagIndex == _tagArr.count | _tagIndex == _tagArr.count - 1) {
        [UIView animateWithDuration:0.2 animations:^{
            _tagSV.contentOffset = CGPointMake(_tagSV.contentSize.width - SCREEN_WIDTH, 0);
            _tagLineView.frame = CGRectMake(sender.frame.origin.x, 37, sender.frame.size.width, 3);
            _mainScrollView.contentOffset = CGPointMake((sender.tag - 3000) * SCREEN_WIDTH, 0);
            [self reparserDataWithIndex:(sender.tag - 3000)];
        }];
        return;
    }
    UIButton *button = _tagButtonArr[_tagIndex];
    CGFloat tagWidth = sender.frame.size.width + button.frame.size.width + 20;
    //判断非最后与非最前的tag的点击事件
    if (button.frame.origin.x - _tagSV.contentOffset.x + button.frame.size.width > SCREEN_WIDTH - 40) {
        [UIView animateWithDuration:0.2 animations:^{
            _tagSV.contentOffset = CGPointMake(sender.frame.origin.x - contentWidth + tagWidth, 0);
            _tagLineView.frame = CGRectMake(sender.frame.origin.x, 37, sender.frame.size.width, 3);
            _mainScrollView.contentOffset = CGPointMake((sender.tag - 3000) * SCREEN_WIDTH, 0);
            [self reparserDataWithIndex:(sender.tag - 3000)];
        }];
        return;
    }else{
        CGFloat x = _tagSV.contentOffset.x - (contentWidth - (button.frame.origin.x - _tagSV.contentOffset.x + button.frame.size.width));
        if (x < 0) {
            [UIView animateWithDuration:0.2 animations:^{
                _tagSV.contentOffset = CGPointMake(0, 0);
                _tagLineView.frame = CGRectMake(sender.frame.origin.x, 37, sender.frame.size.width, 3);
                _mainScrollView.contentOffset = CGPointMake((sender.tag - 3000) * SCREEN_WIDTH, 0);
                [self reparserDataWithIndex:(sender.tag - 3000)];
            }];
            return;
        }
        [UIView animateWithDuration:0.2 animations:^{
            _tagSV.contentOffset = CGPointMake(x, 0);
            _tagLineView.frame = CGRectMake(sender.frame.origin.x, 37, sender.frame.size.width, 3);
            _mainScrollView.contentOffset = CGPointMake((sender.tag - 3000) * SCREEN_WIDTH, 0);
            [self reparserDataWithIndex:(sender.tag - 3000)];
        }];
        return;
    }
}


   //*************scrollview代理方法*************//

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
    UIButton *button = (UIButton *)[self.view viewWithTag:3000 + index];
    [self changeMoments:button];
    [self reparserDataWithIndex:index];
}


   //*************滑动后的数据请求*************//

- (void)reparserDataWithIndex:(NSInteger)index{
    if (_sign == 1) {
        _sign = 2;
            [_secDataArr removeAllObjects];
        [_secTypeVC.tableView reloadData];
        [self parserDataWithIndex:index];
        _typeVC.tableView.frame = CGRectMake(SCREEN_WIDTH * index, 10, SCREEN_WIDTH, SCREEN_HEIGHT - 163);
    }else{
        _sign = 1;
            [_dataArr removeAllObjects];
        [_typeVC.tableView reloadData];
        [self parserWithOtherIndex:index];
        _secTypeVC.tableView.frame = CGRectMake(SCREEN_WIDTH * index, 10, SCREEN_WIDTH, SCREEN_HEIGHT - 163);
    }
}

   //*************跳转到下级界面的代理方法*************//

- (void)jumpToNextView{
    _fstTVC = [[SYMomentsFirstTableViewController alloc]initWithStyle:UITableViewStyleGrouped];
    _fstTVC.urlModel = self.urlModel;
    _fstTVC.urlIndex = self.urlIndex;
    _fstTVC.naviTitle = _naviTitle;
    _fstTVC.arrIndex = _mainScrollView.contentOffset.x / SCREEN_WIDTH;
    if (_sign == 2) {
        _fstTVC.typeModel = _dataArr[self.urlIndex];
    }else{
        _fstTVC.typeModel = _secDataArr[self.urlIndex];
    }
    [self.navigationController pushViewController:_fstTVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
